<template>

    <section>
        <!--产品详情查看-->
        <div>
            <el-col :span="16" :push="1" class="toolbar" style="padding-bottom: 0px; ">

                <!--<el-form label-width="140px"
                         class="demo-fundProduct">
                    <div class="product-row">
                        <el-col :span="20" :push="1">

                            <el-form-item label="产品类型:">
                                <el-select v-model="productType" size="18px" @change="resetValid">
                                    <el-option :key="value" :label="txt" :value="value"
                                               v-for="(txt, value) in options.contract_type"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </div>
                </el-form>-->


                <el-form v-if="productType != 4" :model="partProduct" :rules="partRules"
                         ref="partProduct" label-width="140px"
                         class="demo-fundProduct">

                    <div class="product-row">
                        <el-col :span="20" :push="1">
                            <el-form-item label="产品名称:" prop="product_name">
                                <el-input type="text" v-model="partProduct.product_name"></el-input>
                            </el-form-item>
                        </el-col>
                    </div>

                    <div class="product-row">
                        <el-col :span="20" :push="1">
                            <el-form-item label="投资期限:" prop="investment_period">
                                <el-select placeholder="投资期限" clearable v-model="partProduct.investment_period"
                                           size="18px">
                                    <el-option :key="value" :label="txt" :value="value"
                                               v-for="(txt, value) in options.investment_period"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </div>

                    <div class="product-row">
                        <el-col :span="20" :push="1">
                            <el-form-item label="预期收益率:" prop="expected_earnings">
                                <el-input type="text" placeholder="%"
                                          v-model="partProduct.expected_earnings"></el-input>
                            </el-form-item>
                        </el-col>
                    </div>

                    <div class="product-row">
                        <el-col :span="20" :push="1">
                            <el-form-item label="最低投资额:" prop="minimum_investment_amount">
                                <el-input type="text" placeholder="元"
                                          v-model="partProduct.minimum_investment_amount"></el-input>
                            </el-form-item>
                        </el-col>
                    </div>

                    <div class="product-row">
                        <el-col :span="20" :push="1">
                            <el-form-item label="客户返还收益方式:" prop="income_return_type">
                                <el-select placeholder="客户返还收益方式" clearable v-model="partProduct.income_return_type"
                                           size="18px">
                                    <el-option :key="value" :label="txt" :value="value"
                                               v-for="(txt, value) in options.income_return_type"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </div>
                </el-form>
                <el-form v-if="productType == 4" :model="fundProduct" :rules="fundRules" ref="fundProduct"
                         label-width="140px" class="demo-fundProduct">

                    <div class="product-row">
                        <el-col :span="20" :push="1">
                            <el-form-item label="产品名称:" prop="product_name">
                                <el-input type="text" v-model="fundProduct.product_name"></el-input>
                            </el-form-item>
                        </el-col>
                    </div>
                    <div class="product-row">
                        <el-col :span="20" :push="1">
                            <el-form-item label="基金管理人:" prop="fund_supervision_manager">
                                <el-input type="text" v-model="fundProduct.fund_supervision_manager"></el-input>
                            </el-form-item>
                        </el-col>
                    </div>
                    <div class="product-row">
                        <el-col :span="20" :push="1">
                            <el-form-item label="资产托管人:" prop="asset_manager">
                                <el-input type="text" v-model="fundProduct.asset_manager"></el-input>
                            </el-form-item>
                        </el-col>
                    </div>
                    <div class="product-row">
                        <el-col :span="20" :push="1">
                            <el-form-item label="协会备案编号:" prop="association_no">
                                <el-input type="text" v-model="fundProduct.association_no"></el-input>
                            </el-form-item>
                        </el-col>
                    </div>
                    <div class="product-row">
                        <el-col :span="20" :push="1">
                            <el-form-item label="基金期限:" prop="fund_term">
                                <el-input type="text" v-model="fundProduct.fund_term"></el-input>
                            </el-form-item>
                        </el-col>
                    </div>
                    <div class="product-row">
                        <el-col :span="20" :push="1">
                            <el-form-item label="运作方式:" prop="manage_type">
                                <el-input type="text" v-model="fundProduct.manage_type"></el-input>
                            </el-form-item>
                        </el-col>
                    </div>
                    <div class="product-row">
                        <el-col :span="20" :push="1">
                            <el-form-item label="基金经理:" prop="fund_manager">
                                <el-input type="text" v-model="fundProduct.fund_manager"></el-input>
                            </el-form-item>
                        </el-col>
                    </div>
                    <div class="product-row">
                        <el-col :span="20" :push="1">
                            <el-form-item label="基金投向:" prop="fund_investment">
                                <el-input type="text" v-model="fundProduct.fund_investment"></el-input>
                            </el-form-item>
                        </el-col>
                    </div>
                    <div class="product-row">
                        <el-col :span="20" :push="1">
                            <el-form-item label="业绩比较基准:" prop="fund_benchmark">
                                <el-input type="text" v-model="fundProduct.fund_benchmark"></el-input>
                            </el-form-item>
                        </el-col>
                    </div>
                    <div class="product-row">
                        <el-col :span="20" :push="1">
                            <el-form-item label="管理人业绩报酬:" prop="fund_manage_profit">
                                <el-input type="text" placeholder="基金年化收益率R"
                                          v-model="fundProduct.fund_manage_profit"></el-input>
                            </el-form-item>
                        </el-col>
                    </div>
                    <div class="product-row">
                        <el-col :span="20" :push="1">
                            <el-form-item label="基金费率:" prop="fund_rate">
                                <el-input type="text" v-model="fundProduct.fund_rate"></el-input>
                            </el-form-item>
                        </el-col>
                    </div>
                    <div class="product-row">
                        <el-col :span="20" :push="1">
                            <el-form-item label="募集账户:" prop="raise_account">
                                <el-input type="text" v-model="fundProduct.raise_account"></el-input>
                            </el-form-item>
                        </el-col>
                    </div>


                    <div class="product-row">
                        <el-col :span="20" :push="1">
                            <el-form-item label="文件上传:" prop="upload_contract">
                                <el-upload class="upload-demo" action="ss" :before-upload="beforeAvatarUpload"
                                           :http-request="httpRequest"
                                           :file-list="fundProduct.attachment_info"
                                           :limit="upload_file_limit" :on-exceed="handleExceed"
                                           :on-remove="handleRemove"><!--:show-file-list="false"-->
                                    <el-button size="small" type="primary">点击上传</el-button>
                                </el-upload>
                            </el-form-item>
                        </el-col>
                    </div>
                </el-form>

                <el-col align="center">
                    <el-button type="primary" @click="view">预览
                    </el-button>
                    <el-button @click="cancel">取消</el-button>
                </el-col>
            </el-col>


            <!-- 产品预览 -->
            <el-dialog title="产品预览" :visible.sync="dialog.partDialogVisible">
                <el-tabs type="border-card">
                    <el-tab-pane>
                        <span slot="label">产品预览</span>
                        <el-form v-loading="dialog.partLoading" :model="partProduct">
                            <el-form-item label="产品名称：" :label-width="dialog.formLabelWidth">
                                <span>{{ partProduct.product_name }}</span>
                            </el-form-item>
                            <el-form-item label="投资期限：" :label-width="dialog.formLabelWidth">
                                <span>{{ formatInvestmentPeriod(partProduct.investment_period) }}</span>
                            </el-form-item>
                            <el-form-item label="预期收益率：" :label-width="dialog.formLabelWidth">
                                <span>{{ partProduct.expected_earnings + "%" }}</span>
                            </el-form-item>
                            <el-form-item label="最低投资额：" :label-width="dialog.formLabelWidth">
                                <span>{{ partProduct.minimum_investment_amount + "元" }}</span>
                            </el-form-item>
                            <el-form-item label="客户返还收益方式：" :label-width="dialog.formLabelWidth">
                                <span>{{ formatIncomeReturnType(partProduct.income_return_type) }}</span>
                            </el-form-item>
                        </el-form>
                    </el-tab-pane>
                </el-tabs>
                <div slot="footer" class="dialog-footer">
                    <el-button type="primary" @click="partSubmit">确定</el-button>
                    <el-button @click="partCancel">取 消</el-button>
                </div>
            </el-dialog>


            <!-- 产品预览 -->
            <el-dialog title="产品预览" :visible.sync="dialog.fundDialogVisible">
                <el-tabs type="border-card">
                    <el-tab-pane>
                        <span slot="label">产品预览</span>
                        <el-form v-loading="dialog.fundLoading" :model="fundProduct"
                                 :label-width="dialog.formLabelWidth">
                            <el-form-item label="产品名称：">
                                <span>{{ fundProduct.product_name }}</span>
                            </el-form-item>
                            <el-form-item label="基金管理人：" :label-width="dialog.formLabelWidth">
                                <span>{{ fundProduct.fund_supervision_manager }}</span>
                            </el-form-item>
                            <el-form-item label="资产托管人：" :label-width="dialog.formLabelWidth">
                                <span>{{ fundProduct.asset_manager }}</span>
                            </el-form-item>
                            <el-form-item label="协会备案编号：" :label-width="dialog.formLabelWidth">
                                <span>{{ fundProduct.association_no }}</span>
                            </el-form-item>
                            <el-form-item label="基金期限：" :label-width="dialog.formLabelWidth">
                                <span>{{ fundProduct.fund_term }}</span>
                            </el-form-item>
                            <el-form-item label="运作方式：" :label-width="dialog.formLabelWidth">
                                <span>{{ fundProduct.manage_type }}</span>
                            </el-form-item>
                            <el-form-item label="基金经理：" :label-width="dialog.formLabelWidth">
                                <span>{{ fundProduct.fund_manager }}</span>
                            </el-form-item>
                            <el-form-item label="基金投向：" :label-width="dialog.formLabelWidth">
                                <span>{{ fundProduct.fund_investment }}</span>
                            </el-form-item>
                            <el-form-item label="业绩比较基准：" :label-width="dialog.formLabelWidth">
                                <span>{{ fundProduct.fund_benchmark }}</span>
                            </el-form-item>
                            <el-form-item label="管理人业绩报酬：" :label-width="dialog.formLabelWidth">
                                <span>{{ fundProduct.fund_manage_profit }}</span>
                            </el-form-item>
                            <el-form-item label="基金费率：" :label-width="dialog.formLabelWidth">
                                <span>{{ fundProduct.fund_rate }}</span>
                            </el-form-item>
                            <el-form-item label="募集账户：" :label-width="dialog.formLabelWidth">
                                <span>{{ fundProduct.raise_account }}</span>
                            </el-form-item>

                            <el-form-item label="附件信息：" :label-width="dialog.formLabelWidth">
                                <div v-for="(item) in upload_file_dic"><span>{{item.name}}</span></div>
                            </el-form-item>
                        </el-form>
                    </el-tab-pane>
                </el-tabs>
                <div slot="footer" class="dialog-footer">
                    <el-button type="primary" @click="fundSubmit">确定</el-button>
                    <el-button @click="fundCancel">取 消</el-button>
                </div>
            </el-dialog>
        </div>
    </section>
</template>

<script>
    import * as api from "../../api/product_api";
    import dict from "../../common/js/dict";
    import {update_file} from '../../api/common';

    export default {
        data() {
            var validIncomeReturnType = (rule, value, callback) => {
                if (value == 3 && this.partProduct.investment_period < 4) {
                    callback(new Error(rule.message));
                } else {
                    callback();
                }
            };
            var validInt = (rule, value, callback) => {
                if (!/^\d+$/.test(value)) {
                    callback(new Error('数值应为0或正整数'));
                } else {
                    callback();
                }
            };
            var validFloat = (rule, value, callback) => {
                if (!/^\d+(?:\.\d{1,2})?$/.test(value)) {
                    callback(new Error('0或正数, 最多两位小数'));
                } else {
                    callback();
                }
            };
            var validLength = (rule, value, callback) => {
                let n = value.length;
                if (n < rule.min || n > rule.max) {
                    callback(new Error(rule.min + '-' + rule.max + '字符'));
                } else {
                    callback();
                }
            };
            return {
                upload_file_dic: [],
                upload_file_limit: 20,
                productType: "",
                fundProduct: {
                    id: "",
                    type: "",
                    product_name: "",
                    fund_supervision_manager: "",
                    asset_manager: "",
                    association_no: "",
                    fund_term: "",
                    manage_type: "",
                    fund_manager: "",
                    fund_investment: "",
                    fund_benchmark: "",
                    fund_manage_profit: "",
                    fund_rate: "",
                    raise_account: "",
                    attachment_info: [],
                    attachment_id_list: []
                },
                partProduct: {
                    id: "",
                    type: "",
                    product_name: "",
                    investment_period: "",
                    expected_earnings: "",
                    minimum_investment_amount: "",
                    income_return_type: ""
                },
                fundRules: {
                    product_name: [
                        {required: true, message: '请输入产品名称', trigger: 'blur'}
                    ],
                    fund_supervision_manager: [
                        {required: true, message: '请输入基金管理人', trigger: 'blur'}
                    ],
                    asset_manager: [
                        {required: true, message: '请输入资产托管人', trigger: 'blur'}
                    ],
                    association_no: [
                        {required: true, message: '请输入协会备案编号', trigger: 'blur'}
                    ],
                    fund_term: [
                        {required: true, message: '请输入基金期限', trigger: 'blur'},
                        {validator: validLength, min: 1, max: 125, trigger: 'blur'}
                    ],
                    manage_type: [
                        {required: true, message: '请输入运作方式', trigger: 'blur'}
                    ],
                    fund_manager: [
                        {required: true, message: '请输入基金经理', trigger: 'blur'}
                    ],
                    fund_investment: [
                        {required: true, message: '请输入基金投向', trigger: 'blur'},
                        {validator: validLength, min: 1, max: 125, trigger: 'blur'}
                    ],
                    fund_benchmark: [
                        {required: true, message: '请输入业绩比较基准', trigger: 'blur'}
                    ],
                    fund_manage_profit: [
                        {required: true, message: '请输入管理人业绩报酬', trigger: 'blur'}
                    ],
                    fund_rate: [
                        {required: true, message: '请输入基金费率', trigger: 'blur'},
                        {validator: validLength, min: 1, max: 125, trigger: 'blur'}
                    ],
                    raise_account: [
                        {required: true, message: '请输入募集账户', trigger: 'blur'},
                        {validator: validLength, min: 1, max: 125, trigger: 'blur'}
                    ]
                },
                partRules: {
                    product_name: [
                        {required: true, message: '请输入产品名称', trigger: 'blur'}
                    ],
                    investment_period: [
                        {required: true, message: '请选择投资期限', trigger: 'blur'}
                    ],
                    expected_earnings: [
                        {required: true, message: '请输入预期收益率', trigger: 'blur'},
                        {validator: validFloat, trigger: 'blur'},
                    ],
                    minimum_investment_amount: [
                        {required: true, message: '请输入最低投资额', trigger: 'blur'},
                        {validator: validInt, trigger: 'blur'},
                    ],
                    income_return_type: [
                        {required: true, message: '请选择客户返还收益方式', trigger: 'blur'},
                        {validator: validIncomeReturnType, message: '当投资期限低于1年时，不得选择“年付”', trigger: 'blur'},
                    ],
                },
                options: {
                    contract_type: dict.contract_type,
                    investment_period: dict.investment_period,
                    income_return_type: dict.income_return_type
                },
                dialog: {
                    fundLoading: false,
                    fundDialogVisible: false,
                    partLoading: false,
                    partDialogVisible: false,
                    formLabelWidth: '150px'
                }
            }
        },
        methods: {
            view() {
                if (this.productType != 4) {
                    this.$refs['partProduct'].validate((valid) => {
                        if (valid) {
                            this.dialog.partDialogVisible = true;
                        }
                    });
                }
                else if (this.productType == 4) {
                    this.$refs['fundProduct'].validate((valid) => {
                        if (valid) {

                            if (this.upload_file_dic && this.upload_file_dic.length > 0) {

                                this.fundProduct.attachment_id_list = [];
                                for (let i = 0; i < this.upload_file_dic.length; i++) {
                                    this.fundProduct.attachment_id_list.push(this.upload_file_dic[i].id);
                                }

                                this.dialog.fundDialogVisible = true;
                            }
                            else {

                                this.$message.error("请至少上传一个附件");
                            }
                        }
                    });
                }
                else {
                    this.$message.error("请选择产品类型并完成表单");
                }
            },
            cancel() {
                this.$router.push('../list');
            },
            partSubmit() {

                this.dialog.partLoading = true;  //显示loading

                let params = this.partProduct;
                params.type = this.productType;

                params.expected_earnings = params.expected_earnings * 10000;
                params.minimum_investment_amount = params.minimum_investment_amount * 100;


                api.productUpdate(params).then((res) => {
                    if (res.data.status == 200) {
                        this.dialog.partLoading = false;  //隐藏loading
                        this.$message({
                            type: 'success',
                            message: '修改成功!'
                        });

                        this.$router.push('../list');
                    } else {
                        if (res.data.status == 401) {
                            this.$router.push('/login');
                        }
                        this.$message.error(res.data.status + " " + res.data.msg);
                    }
                });
            },
            partCancel() {
                this.dialog.partDialogVisible = false;

            },
            fundSubmit() {

                this.dialog.fundLoading = true;  //显示loading

                let params = this.fundProduct;
                params.type = this.productType;
                params.attachment_info = [];
                api.productUpdate(params).then((res) => {
                    if (res.data.status == 200) {
                        this.dialog.fundLoading = false;  //隐藏loading

                        this.$message({
                            type: 'success',
                            message: '修改成功!'
                        });

                        this.$router.push('../list');


                    } else {
                        if (res.data.status == 401) {
                            this.$router.push('/login');
                        }
                        this.$message.error(res.data.status + " " + res.data.msg);
                    }
                });
            },
            fundCancel() {
                this.dialog.fundDialogVisible = false;
            },
            formatInvestmentPeriod(val) {
                return this.options.investment_period[val];
            },
            formatIncomeReturnType(val) {
                return this.options.income_return_type[val];
            },
            loadProduct() {
                let params = {
                    id: this.$route.params.id
                };

                api.productInfo(params).then((res) => {
                    let result = JSON.parse(res.data.datas);
                    if (res.data.status == 200) {

                        this.productType = result.type;
                        if (this.productType != 4) {

                            result.investment_period = result.investment_period.toString();
                            result.income_return_type = result.income_return_type.toString();
                            result.expected_earnings = result.expected_earnings / 10000;
                            result.minimum_investment_amount = result.minimum_investment_amount / 100;

                            this.partProduct = result;
                        }
                        else {
                            this.fundProduct = result;

                            this.attachmentInfoInit();
                        }


                    } else {
                        if (res.data.status == 401) {
                            this.$router.push('/login');
                        }
                        this.$message.error(res.data.status + " " + res.data.msg);
                    }
                });

            },
            attachmentInfoInit() {
                if (this.fundProduct.attachment_info && this.fundProduct.attachment_info.length > 0) {
                    if (this.fundProduct.attachment_info[0].uid) {
                        this.upload_file_dic = [];
                        for (let i = 0; i < this.fundProduct.attachment_info.length; i++) {
                            let file_item = {
                                name: this.fundProduct.attachment_info[i].name,
                                id: this.fundProduct.attachment_info[i].id,
                                uid: this.fundProduct.attachment_info[i].uid
                            };
                            this.upload_file_dic.push(file_item);
                        }
                    }
                    else {
                        setTimeout(this.attachmentInfoInit, 50);
                    }
                }

            },
            /* -------------------------------------- 上传文件 --------------------------------------------------  */
            // 上传前对文件的大小的判断
            beforeAvatarUpload(file) {
                const extension = file.name.split('.')[1] === 'pdf';
                const isLt2M = file.size / 1024 / 1024 < 2
                if (!extension) {
                    this.$message.error('上传模板只能是本地 pdf 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传模板大小不能超过 2MB!');
                }
                return extension && isLt2M;
            },
            handleExceed(files, fileList) {
                this.$message.warning(`当前限制选择 20 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
            },
            handleRemove(file, fileList) {

                if (this.upload_file_dic && this.upload_file_dic.length > 0) {
                    let uid = file.uid;
                    for (let i = this.upload_file_dic.length - 1; i >= 0; i--) {
                        if (this.upload_file_dic[i].uid == uid) {
                            this.upload_file_dic.splice(i, 1);
                        }
                    }

                }

            },
            httpRequest(item) {
                let formData = new FormData();
                formData.append('file', item.file);
                formData.append('roleType', "1");

                formData.append('fileName', item.file.name);
                let user = JSON.parse(sessionStorage.getItem("user"));
                formData.append('roleId', user.id);
                update_file(formData).then((res) => {
                    let result = JSON.parse(res.data.datas);
                    if (res.data.status === 200) {
                        let file_item = {
                            name: item.file.name,
                            id: result.id,
                            uid: item.file.uid
                        };
                        this.upload_file_dic.push(file_item);
                    } else {
                        if (res.data.status === 401) {
                            this.$router.push('/login');
                        }
                        this.$message.error(res.data.msg);
                    }
                });
            }
        },
        mounted() {
            this.$nextTick(function () {
                this.loadProduct(); //初始化页面数据
            });
        }

    }
</script>

<style scoped>

    .product-row {
        width: 100%;
        float: left;
        margin-bottom: 10px;
    }
</style>